---
category: String
created: '2020-05-29'
title: Truncate a string at full words
updated: '2021-10-13'
---

**JavaScript version**

```js truncate.js
const truncate = (str, max, suffix) =>
    str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;
```

**TypeScript version**

```ts truncate.ts
const truncate = (str: string, max: number, suffix: string = '...'): string =>
    str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;
```

**Examples**

```js examples.js
truncate('This is a long message', 20, '...'); // 'This is a long...'
```
